import {
  ds
} from "../../../../tools/data"
import {
  ui
} from "../../../../tools/ui"
import {
  checkTool
} from "../../../../tools/check"
import {
  pages
} from "../../../../tools/pages"
Page({
  data: {
    mod: {},
    id: '', // from options
  },
  async init() {
    const that = this,
      _ = ds.cmd
    ds.coll('module')
      .where({
        _id: _.eq(this.data.id)
      })
      .orderBy('pos', 'asc')
      .get({
        success: function (res) {
          that.setData({
            mod: res.data[0]
          })
        }
      });
  },
  addSwiper(e) {
    const data = this.data
    wx.navigateTo({
      url: `edit/index?id=${data.id}`,
    })
  },
  editSwiper(e) {
    const index = ui.eventData(e, 'index')
    const mod = this.data.mod
    wx.navigateTo({
      url: `edit/index?action=edit&id=${mod._id}&index=${index}`,
    })
  },
  onDeleteTap(e) {
    const index = ui.eventData(e, 'index')
    const mod = this.data.mod
    mod.slides.splice(index, 1)
    this.setData({
      'mod.slides': mod.slides
    })
  },
  dayInputChange(e) {
    const mod = this.data.mod
    mod.dayNum = e.detail.value
    this.setData({
      mod
    })
  },
  backTap() {
    pages.back(pre => {
      pre.init()
    })
  },
  saveTap() {
    ui.loading();
    const {
      id,
      mod
    } = this.data
    checkTool.check([{
      title: "弹出天数",
      regex: checkTool.CommonRegex.integer,
      value: mod.dayNum
    }])
    mod.dayNum = parseInt(mod.dayNum)
    ds.cloudUpdate('module', id, mod, res => {
      ui.loading(false)
      const success = res.result.errMsg.endsWith(":ok")
      if (success) pages.back(prePage => {
        prePage.init()
      })
    })
  },
  onChangePosInput(e) {
    this.setData({
      'mod.pos': e.detail.value
    })
  },
  onLoad(option) {
    this.setData({
      id: option.id
    });
    this.init(true);
  },
});